define(function(require){
    $(function(){
    	/*---------- 媒体管理——管理员 ----------*/
    	
        /* 媒体数据-Table */
    	var bodyTemplate = ['<tr media_id="{id}">',
	                    		'<td class="txtc"><a href="/trp/position/main/?mediaId={id}" title="{media_name}">{media_name}</a></td>',
	                    		'<td class="txtc">{type}</td>',
	                    		'<td class="txtc">{media_attrs}</td>',
    	                     	'<td class="txtc">',
    	                     		'<a class="ibtn showchart" href="javascript:;" title="查看报表"><span class="glyphicon glyphicon-list-alt"></span></a>',
    	                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
    	                     		'<a class="ibtn delbtn {disabled}" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove"></span></a>',
	                     		'</td>',
    	                     '</tr>'].join('');
    	 
    	 var grid = Grid.init({
            holder:'mediaResources',
            dataSource:'/trp/media/get_list',
            bodyTemplate:bodyTemplate,
            pageTemplate:semi.grid.pageTemplate,
            sendOnPageSize: true
    	 });
    	//数据重置：媒体类型   0站内    1站外    2联盟
    	//can_deleted,1代表可以删除，0表示不能删除
     	grid.modifyModel(function(data){
         	if(data.type==0){
         		data.type = '站内';
         	}else if(data.type==1){
         		data.type = '站外';
         	}else{
         		data.type = '联盟';
         	}
         	var disabled = '';
         	if(data.can_deleted != 1){
         		disabled = 'disabled';
         	}
         	$.extend(data, {
         		disabled: disabled
         	});
     	});
     	
     	grid.onfilled(function(data){
     		grid.data = data;
     		$('.delbtn.disabled').attr('title','请先清空媒体下广告位');
     		$('.ibtn').tooltip();
     	});
    	 //数据搜索
         var filterData = function(pno){
         	var txt = $('.searchbox-ipt').val(), pageSize = 20;
         	if($('select.page-size').size()>0){
         		pageSize = $('select.page-size').val();
         	}
             grid.send({
            	searchText: txt,
            	type: $('.pageheader [name=media_type]').val(),
         		pageSize: pageSize,
         		pageNo: pno || 1
         	});
         };
         filterData();
         
         //按名称、属性模糊搜索
         $('.pageheader .searchbox-btn').on('click', function(){
        	 filterData();
         });
         $('.pageheader .searchbox-ipt').on('keyup', function(e){
         	if(e.keyCode==semi.keyCode.ENTER){
         		filterData();
         	}
         });
         
         //按媒体类型搜索
         $('.pageheader [name=media_type]').on('change', function(){
        	 filterData();
         }).select2();
    	 
    	 var temp_attrsOp = '';
    	 var getAttrs = function(callback){
    		 $ajax.ajax({
        		 url: '/trp/media/get_attrs',
        		 success: function(data){
        			 temp_attrsOp = '';
        			 $.each(data.data, function(i,n){
        				 temp_attrsOp += '<option value="'+n.id+'">'+n.name+'</option>'
        			 });
        			 if(!semi.utils.isEmpty(callback) && $.isFunction(callback))callback.call(this, temp_attrsOp);
        		 }
        	 });
    	 }
    	 
    	 var initAttrs = function($node){
    		 $('[name=media_attrs]',$node).append(temp_attrsOp).select2({
				formatResult: function(state) {
				    return state.text + '<a class="pull-right red delattr" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove font12"></span></a>';
				},
			    allowClear: true
		    }).on('select2-selecting', function(e){
		    	var isdel = $(e.target).data('delattr');
		    	if(!semi.utils.isEmpty(isdel) && isdel){
		    		$(e.target).data('delattr',false);
		    		$('[name=media_attrs]',$node).select2('close');
		    		semi.utils.stopDefault(e);
		    		$ajax.ajax({
		    			url: '/trp/media/check_attr/',
		    			data: {
		    				id: e.val
		    			},
		    			success: function(data){
		    				//tag:0(不存在）、tag:1（存在）
		    				seajs.log(data.tag);
		    				var $dlg = $dialog.confirm({
		                		title: '媒体属性删除',
		                        content: '媒体属性 【'+e.choice.text+'】 '+(data.tag?'<b class="red">有</b>':'<b>无</b>')+'关联的媒体，您确定要删除该属性吗？',
		                        ok: function(){
		                        	var $dlg = this;
		                        	$ajax.ajax({
		                        		url: '/trp/media/delete_attr/',
		                        		data: {
		                        			id: $dlg.id
		                        		},
		                                success: function(){
		                                	$('[name=media_attrs] [value='+$dlg.id+']',$node).remove();
		                                	$dlg.close().remove();
		                                	//$dialog.alert('删除媒体属性成功！','success');
		                                },
		        	                    error: function(){
		        	                    	$dlg.close().remove();
		        	                    	$dialog.alert('删除媒体属性失败，请稍后重试！','warning');
		        	                    }
		                        	});
		                        	return false;
		                        }
		                	});
		                	$.extend($dlg,{id:e.val});
		    			}
		    		});
		    	}
		    });
    	 }
    	 $(document).on('mouseenter','.delattr',function(){
    		 $('.ui-dialog-content [name=media_attrs]').data('delattr',true);
    	 });
    	 $(document).on('mouseleave','.delattr',function(){
    		 $('.ui-dialog-content [name=media_attrs]').data('delattr',false);
    	 });
        
        /* 新增媒体-dialog */
        require('validate');
        $('.createmedia').on('click', function(){
        	var $dlg = $dialog({
        		id: 'popMedia',
                title: '新增媒体',
                width: '500px',
            	onshow: function(){
            		var $d = this, $node = $($d.node);
            		getAttrs(function(){
            			$d.content($('.pop-createmedia').clone().show()[0]);
        				initAttrs($node);
        				$('[name=media_type]',$node).select2();
        			});
            	},
            	okValue: '确定',
            	ok: function(){
            		var $node = $(this.node);
            		if(!$('form',$node).valid())return false;
            		$ajax.ajax({
            			url : '/trp/media/create/',
                		data: JSON.stringify({
                    		media_name: $('[name=media_name]',$node).val(),
                    		type: $('[name=media_type]',$node).val(),
                    		media_attrs: $('[name=media_attrs]',$node).val()||[]
        				}),
                		contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('新增媒体成功！','success');
                        	filterData();
                        },
                        error: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('新增媒体失败，请稍后重试！','warning');
                        }
                	 });
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        	
        });
        
        /* 修改媒体-dialog */
        $(document).on('click', '.editbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), media_id = $tr.attr('media_id');
        	var $dlg = $dialog({
        		id: 'popMedia',
                title: '修改媒体',
                width: '500px',
            	onshow: function(){
            		var $d = this, $node = $($d.node);
            		$ajax.ajax({
            			url: '/trp/media/get',
            			data: {
            				id: media_id
            			},
            			success: function(data){
                    		getAttrs(function(){
                    			$d.content($('.pop-createmedia').clone().show()[0]);
                				initAttrs($node);
                				$('[name=media_type]',$node).select2();
                				
                				
                				$('[name=media_name]',$node).val(data.name);
                				var attrArr = [];
                				$.each(data.data, function(i,n){
                					attrArr.push(n.id);
                				});
                				$('[name=media_attrs]',$node).select2('val', attrArr);
                				$('[name=media_type]',$node).select2('val', data.type);
                			});
                    		
                    		
            				/*getAttrs(function(){
                				$d.content($('.pop-createmedia').clone().show()[0]);
                				$('[name=media_name]',$node).val(data.name);
                				$('[name=media_attrs]',$node).append(temp_attrsOp);
                				$.each(data.data, function(i,n){
                					$('option[value='+n.id+']',$node).attr('selected','selected');
                				});
                				$('[name=media_attrs]',$node).select2({allowClear: true});
                			});*/
            			}
            		});
            	},
                okValue: '确定',
                ok: function(){
            		var $node = $(this.node);
            		if(!$('form',$node).valid())return false;
            		$ajax.ajax({
            			url : '/trp/media/update/',
                		data: JSON.stringify({
                        	media_id: media_id,
                    		media_name: $('[name=media_name]',$node).val(),
                    		type: $('[name=media_type]',$node).val(),
                    		media_attrs: $('[name=media_attrs]',$node).val()||[]
        				}),
                		contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('修改媒体成功！','success');
                        	filterData(semi.utils.gridPage(grid));
                        }
                	 });
                	return false;
                },
                cancelValue: '取消',
                cancel: true
            }).showModal();
        	
        });
        
        
        /* 删除媒体-dialog */
        $(document).on('click', '.delbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), media_id = $tr.attr('media_id');
        	if($this.hasClass('disabled'))return;
        	var $dlg = $dialog.confirm({
        		title: '删除媒体',
                content: '您确定要删除该媒体吗？',
                ok: function(){
                	var $dlg = this;
                	$ajax.ajax({
                    	url: '/trp/media/delete/',
                        data: {
                        	media_id: $dlg.media_id
        				},
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert('删除媒体成功！','success');
                        	filterData(semi.utils.gridPage(grid));
                        }
                    });
                	return false;
                }
        	});
        	$.extend($dlg,{media_id:media_id});
        	
        });
        
        /* 媒体报表-dialog */
        var $popchart = require('./common/popchart');
        $(document).on('click', '.showchart', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), media_id = $tr.attr('media_id');
        	$popchart({
            	title: '媒体报表',
            	btn: $this,
            	dataurl: '/trp/media/report',
            	type: 'media',
            	idname: 'media_id',
            	idvalue: media_id
            });
        });
        
        /* 新增媒体属性 */
        $(document).on('click', '.createattr', function(){
        	var $curnode = $($dialog.get('popMedia').node),
        		$dlg = $dialog({
	                title: '新增媒体属性',
	                content: $('.pop-createattr').clone().show()[0],
	                width: '500px',
    				zIndex: semi.utils.topIndex(),
	            	okValue: '确定',
	            	ok: function(){
	            		var $node = $(this.node), name = $('[name=attr_name]',$node).val();
	            		if(!$('form',$node).valid())return false;
	            		var repeat = false;
	            		$('[name=media_attrs] option',$curnode).each(function(){
	            			if($(this).text()==name)repeat = true;
	            		});
	            		if(repeat){
	            			$('[name=attr_name]',$node).addClass('error').siblings('label.error').remove();
	            			$('[name=attr_name]',$node).after('<label for="attr_name" generated="true" class="error">此属性已存在</label>');
	            			return false;
	            		}
	            		$ajax.ajax({
	            			url : '/trp/media/create_attr/',
	                		data: {
	                			name: name,
	        				},
	                        success: function(data){
	                        	$dlg.close().remove();
	                        	if($('[name=media_attrs]',$curnode).children().size()>0){
	                        		$('[name=media_attrs]',$curnode).children(':first').before('<option value="'+data.id+'">'+name+'</option>');
	                        	}else{
	                        		$('[name=media_attrs]',$curnode).append('<option value="'+data.id+'">'+name+'</option>');
	                        	}
	                        	//$dialog.alert('新增媒体成功！','success');
	                        },
	                        error: function(){
	                        	$('[name=attr_name]',$node).addClass('error').siblings('label.error').remove();
		            			$('[name=attr_name]',$node).after('<label for="attr_name" generated="true" class="error">此属性已存在</label>');
	                        	//$dlg.close().remove();
	                        	//$dialog.alert('新增媒体失败，请稍后重试！','warning');
	                        }
	                	 });
	                	return false;
	                },
	                cancelValue: '取消',
	                cancel: true
	            }).showModal();
        });
    });
});